﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.Xrm.Sdk.Query;

namespace CrmClient.Query
{
    internal class CrmLink
    {
        public CrmLinkAlias Alias { get; private set; }

        public string FromEntityName { get; private set; }

        public string FromCrmAttrName { get; private set; }

        public string ToCrmAttrName { get; private set; }

        public string[] ToEntityCrmAttrs { get; private set; }

        public JoinOperator JoinOperator { get; private set; }

        public FilterExpression Filter { get; private set; }

        public CrmLink(CrmLinkAlias alias, string fromEntityName, string fromCrmAttrName, string toCrmAttrName, IEnumerable<string> toEntityCrmAttrs, JoinOperator joinOperator, 
            FilterExpression filter)
        {
            Alias = alias;
            FromEntityName = fromEntityName;
            FromCrmAttrName = fromCrmAttrName;
            ToCrmAttrName = toCrmAttrName;
            ToEntityCrmAttrs = toEntityCrmAttrs.ToArray();
            JoinOperator = joinOperator;
            Filter = filter;
        }

        public CrmLink Clone()
        {
            return new CrmLink(Alias, FromEntityName, FromCrmAttrName, ToCrmAttrName, ToEntityCrmAttrs, JoinOperator, Filter);
        }

        public LinkEntity CreateLinkEntity()
        {
            var res = new LinkEntity(FromEntityName, Alias.EntityName, FromCrmAttrName, ToCrmAttrName, JoinOperator);
            res.EntityAlias = Alias.ToString();
            res.Columns = new ColumnSet(ToEntityCrmAttrs);
            res.LinkCriteria = Filter;
            return res;
        }
    }
}
